package com.glqiang.config;

import com.glqiang.filter.CustomOncePerRequestFilter;
import com.glqiang.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.Arrays;

/**
 * @author glq1218
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    /**
     * 手机号验证服务
     */
    @Autowired
    private AuthenticationProvider phoneAuthenticationProvider;

    @Autowired
    private CustomOncePerRequestFilter customOncePerRequestFilter;

    private AuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(customUserDetailsService);
        return daoAuthenticationProvider;
    }

    /**
     * 密码加密规则 强散列哈希加密实现(密码加密算法)
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) {
        return new ProviderManager(Arrays.asList(daoAuthenticationProvider(), phoneAuthenticationProvider));
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {

        return httpSecurity
                // 允许跨域
                .cors().and()
                // 关闭默认登出
                .logout().disable()
                // 关闭csrf
                .csrf().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                // 允许匿名访问
                .antMatchers(antMatchersAnonymous()).anonymous()
                // 静态资源不需要任何限制
                .antMatchers(HttpMethod.GET, antMatchersPermitAll()).permitAll()
                // 需要登录才可以访问
                .antMatchers("/logout").authenticated()
                // 除上面外的所有请求全部不需要鉴权认证
                .anyRequest().permitAll().and()
                // 告诉security如何处理异常
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler).and()
                .addFilterBefore(customOncePerRequestFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    /**
     * 允许匿名访问url
     *
     * @return 字符串数组
     */
    private String[] antMatchersAnonymous() {
        return new String[]{"/login"};
    }

    /**
     * 不需要任何限制url（静态资源）
     *
     * @return 字符串数组
     */
    private String[] antMatchersPermitAll() {
        return new String[]{"/*.html"};
    }


}
